import EventEmitter from 'eventemitter3';
import util from "./util";
import request from "./util/request";
import logger from "./helper/logger";
import Store from './store';
import Hooks from './hooks';
import Types from './types';
import Context from './context';
export default class Applaction extends EventEmitter {
  constructor(options = {}, container) {
    super();
    this.options = options;
    this.container = container;

    // 工具相关
    this.util = util;
    this.logger = logger;
    this.request = request(this);

    this.hooks = Object.create(null); // 默认hooks为空对象
    this.plugins = []; // 默认plugins为空数组
    this.initLoadedPlugins = []; // 默认plugins为空数组
    this.init();
  }

  init() {
    const TAG = `初始化${this.constructor.name}`
    this.logger.time(TAG)

    // 挂载核心
    new Types(this);
    new Hooks(this);
    this.store = new Store();
    this.logger.timeEnd(TAG);
  }

  get state() {
    return this.store.state || {}; // 默认state为空对象
  }

  run(fn) {
    // 初始化插件
    const TAG = `初始化plugins插件`;
    this.logger.time(TAG)
    // 初始化事件监听
    this.on('initLoaded', () => {
      this.initLoadedPlugins.forEach(plugin => plugin.init());
    })
    this.plugins.forEach(plugin => plugin.init());
    this.logger.timeEnd(TAG)

    // 运行app
    fn && fn(this);
    return this;
  }

  // 所有use使用都是基于isBefore
  use(Instance, options = {}) {
    if (typeof Instance !== 'function') {
      throw Error('插件必须是可实例对象')
    }
    const { isBefore } = options;
    const instance = new Instance(this, options);
    if (!instance instanceof Context) {
      throw Error('类必须继承Context');
    }
    if (isBefore) {
      this.plugins.push(instance);
    } else {
      this.initLoadedPlugins.push(instance)
    }
    return this;
  }

  // cnzz事件统计
  cnzzEvent(name) {
    if (!_czc) return;
    const agent = this.util.isMobileHanddle() ? 'wap' : 'pc';
    _czc.push(['_trackEvent', `${agent}_统计事件`, name]);
  }
}
